const cheerio = require('cheerio')
const { request, request2 } = require('./request')
const tag = '回帖' // 回帖子
const { getTBS, getTBS2 } = require('./utils')

let requestInterval = 350

// 删除多个
async function deleteMultiple(config, ws, webconfig) {

  let { start, end, interval } = config
  requestInterval = interval || 350
  if (!start || !end) {
    if (start) {
      end = start
    } else if (end) {
      start = end
    } else {
      sendMessage(`${tag}: 请设置开始和结束页 `, ws)
      return false
    }
  } else if (start > end) {
    start = end
  }

  const list = await getMultiplePage(start, end, ws, webconfig)
  const len = list.length
  if (len === 0) {
    sendMessage(`${tag}: 完成`, ws)
    return false
  }

  for (let index = 0; index < list.length; index++) {
    sendMessage(`${tag}: 开始删除回帖>${list[index].title} : ${list[index].reply}`, ws)
    const status = await deleteOne(list[index], ws, webconfig)
    if (status !== true && status && status.err_code == 220034) {
      sendMessage(`${tag}: >>> 删除限制 <<< , 请明天再尝试`, ws)
      return false
    }
    if (webconfig && webconfig.isRunning === "NO") {
      return false
    }
  }
  sendMessage(`${tag}: 完成`, ws)
}

// 删除一个
async function deleteOne(params, ws, webconfig) {
  let tbs
  if (ws) {
    tbs = await getTBS2(webconfig.cookie)
  } else {
    tbs = await getTBS()
  }
  if (!tbs) {
    console.log(`${tag}: 请重新登陆，并设置cookie! `)
    return false
  }

  const fd = new URLSearchParams()
  Object.keys(params).forEach(key => {
    // fd.append(key, params[key])
    fd.append('tid', params.tid)
    fd.append('pid', params.pid)
    fd.append('tbs', tbs)
    fd.append('ie', 'utf-8')
  })


  const url = 'https://tieba.baidu.com/f/commit/post/delete'
  const response = await sendRequest(url, fd, webconfig)

  const data = await response.json()

  return new Promise(resolve => {
    setTimeout(() => {
      let message
      if (data.err_code === 0) {
        message = `${tag}: 删除成功`
        resolve(false)
      } else {
        message = `${tag}: 删除错误:` + JSON.stringify(data)
        resolve(data)
      }
      sendMessage(message, ws)
    }, requestInterval)
  })
}

// 获取多页
async function getMultiplePage(start, end, ws, webconfig) {
  sendMessage(`${tag}: 获得, 页面:${start}->${end}`, ws)
  const data = []
  for (let page = start; page <= end; page++) {
    let list = await getOnePage(page)
    data.push(...list)
  }
  sendMessage(`${tag}: 获得总数: ${data.length}`, ws)
  return data
}

// 获取一页评论
async function getOnePage(page, ws, webconfig) {
  const url = `https://tieba.baidu.com/i/i/replyme?&pn=${page}`
  const response = await sendRequest(url, null, webconfig)
  console.log("zhei...")
  const data = await response.text()
  const $ = cheerio.load(data)

  const list = $('div.feed_item__clearfix__feed_replyme__j_feed_replyme').map((index, el) => {

    let title = $(el).find('a.thread_title').text()
    let reply = $(el).find('div.replyme_content').find('a').text()
    let param = $(el).find('a.reply_del').attr('data-param')
    console.log(param)
    // let is_finf =
    // let fid =
    // let kw =
    // let tbs =
    // let is_vipdel =
    return { tid, pid, title, reply }
  });
  // pid 发帖ID
  // tid 回复ID

  return new Promise(resolve => {
    setTimeout(() => {
      sendMessage(`${tag}: 获得, 页面:${page}, 数量:${list.length}`, ws)
      resolve(list)
    }, requestInterval)
  })
}

// 输出消息
async function sendMessage(message2, ws) {
  if (typeof ws !== "undefined" && ws !== null) {
    ws.send(JSON.stringify({ status: 'message', message: message2 }));
  } else {
    // console.log(message2)
  }
  console.log(message2)
}

// 发送请求
async function sendRequest(url, fb, webconfig) {
  if (typeof webconfig !== "undefined" && webconfig !== null) {
    return await request2(url, webconfig.cookie, fb)
  } else {
   return await request(url,fb)
  }
}

module.exports.deleteReplies = deleteMultiple
